using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Kannon.Core
{
    public class KannonResponse
    {
        public HttpStatusCode StatusCode
        { get; set; }

        public string StatusDescription
        { get; set; }

        public HttpResponseHeaderCollection Headers
        { get; private set; }

        public Stream OutputStream
        { get; set; }

        public KannonResponse(HttpStatusCode statusCode) :
            this(statusCode, null)
        {
        }

        public KannonResponse(HttpStatusCode statusCode, IDictionary<string, string> headers) :
            this(statusCode, headers, null)
        {
        }

        public KannonResponse(HttpStatusCode statusCode, IDictionary<string, string> headers, Stream output) :
            this(statusCode, null, headers, output)
        {
        }

        public KannonResponse(HttpStatusCode statusCode, string statusDescription, IDictionary<string, string> headers, Stream output)
        {
            StatusCode = statusCode;
            StatusDescription = statusDescription ?? statusCode.ToString();
            Headers = new HttpResponseHeaderCollection(headers ?? new Dictionary<string, string>());
            OutputStream = output;
        }

        public static implicit operator KannonResponse(string response)
        {
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(response));

            return new 
                KannonResponse(HttpStatusCode.OK) {
                    Headers = {
                        { HttpResponseHeader.ContentType, "text/html; charset=utf-8" },
                        { HttpResponseHeader.ContentLength, stream.Length.ToString() }
                    },
                    OutputStream = stream 
                };
        }

        public static implicit operator KannonResponse(HttpStatusCode statusCode)
        {
            return new KannonResponse(statusCode);
        }

        public static implicit operator KannonResponse(Uri uri)
        {
            return new KannonResponse(HttpStatusCode.Found) {
                Headers = { { HttpResponseHeader.Location, uri.OriginalString } }
            };
        }
    }
}